package com.fhz.module_main;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.fragment.NavHostFragment;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.StringUtils;
import com.fhz.core_lib.entity.LoggedInUser;
import com.fhz.core_lib.mvvm.BaseMVVMActivity;
import com.fhz.core_lib.router.RouterActivityPath;
import com.fhz.core_lib.router.RouterFragmentPath;
import com.fhz.core_lib.utils.SPUtils;
import com.fhz.module_main.adapter.MainPageAdapter;
import com.fhz.module_main.databinding.ActivityMainModuleBinding;
import com.fhz.module_main.utils.AppSettings;
import com.fhz.module_main.utils.ColorUtils;
import com.gyf.barlibrary.ImmersionBar;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;
import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener;

@Route(path = RouterActivityPath.Main.PAGER_MAIN)
public class MainActivity extends BaseMVVMActivity<MainActivityViewModel, ActivityMainModuleBinding> {

    private List<Fragment> fragments;

    private MainPageAdapter adapter;

    private NavigationController mNavigationController;

    private RxPermissions permissions;

    @Autowired(name = "user")
    LoggedInUser user;


    @Override
    protected MainActivityViewModel createViewModel() {
        return new ViewModelProvider(this).get(MainActivityViewModel.class);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main_module;
    }

    @Override
    protected void initView() {
        super.initView();

        AppSettings instance = AppSettings.getInstance(this);


        permissions = new RxPermissions(this); //10m 1m 收空 引用

        //权限申请
        permissions.request(Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CALL_PHONE
        ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (!aBoolean) {
                    Toast.makeText(MainActivity.this, "必须都要同意哦", Toast.LENGTH_SHORT).show();
                }
            }
        });


//        ImmersionBar.with(this)
//                    .statusBarColor(R.color.main_color_bar)
//                .navigationBarColor(R.color.main_color_bar)
//                .fitsSystemWindows(true)
//                .transparentNavigationBar()
//                .autoDarkModeEnable(true)
//                .init();

        mNavigationController = binding.bottomView.material()
                .addItem(R.drawable.main_home,
                        "首页",
                        ColorUtils.getColor(this, R.color.main_bottom_check_color))
                .addItem(R.drawable.main_community,
                        "社区",
                        ColorUtils.getColor(this, R.color.main_bottom_check_color))
                .addItem(R.drawable.main_notify,
                        "通知",
                        ColorUtils.getColor(this, R.color.main_bottom_check_color))
                .addItem(R.drawable.main_user,
                        "我的",
                        ColorUtils.getColor(this, R.color.main_bottom_check_color))
                .setDefaultColor(
                        ColorUtils.getColor(this, R.color.main_bottom_default_color))
                .enableAnimateLayoutChanges()
                .build();
        mNavigationController.setHasMessage(2, true);
        mNavigationController.setMessageNumber(3, 6);
        adapter = new MainPageAdapter(getSupportFragmentManager(),
                FragmentPagerAdapter.BEHAVIOR_SET_USER_VISIBLE_HINT);
        binding.cvContentView.setOffscreenPageLimit(1);
        binding.cvContentView.setAdapter(adapter);
        mNavigationController.setupWithViewPager(binding.cvContentView);

//        mNavigationController.setSelect(3,true);
        mNavigationController.addTabItemSelectedListener(new OnTabItemSelectedListener() {
            @Override
            public void onSelected(int index, int old) {
                if(index == 3){
                    /**
                     * 判断是否登录
                     * 1,从sp中取值,
                     * 2,如果空,就去登录页面
                     * 3,如果有值,就跳转到真实的fragment
                     */
                    //1.从sp中取值
                    String nickname = SPUtils.getInstance().getString(SPUtils.NICKNAME, "");
                    //也可以验证一下token的有效期
                    if(StringUtils.isEmpty(nickname)){
                       //2.跳转到登录页面
                        mNavigationController.setSelect(old);
                        ARouter.getInstance().build(RouterActivityPath.User.PAGER_LOGIN).navigation();
                        return;
                    }
                    // 3.设置页面
                    mNavigationController.setSelect(3);
                }
            }

            @Override
            public void onRepeat(int index) {

            }
        });


        initFragment();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Fragment mineFragment = (Fragment) ARouter.getInstance().build(RouterFragmentPath.Mine.PAGE_MINE).navigation();
        mineFragment.onActivityResult(requestCode,resultCode,data);

    }
    //找到指定的fragment
    public Fragment getFragment(Class<?> clazz) {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments!= null && fragments.size() > 0) {
            NavHostFragment navHostFragment = (NavHostFragment) fragments.get(0);
            List<Fragment> childfragments = navHostFragment.getChildFragmentManager().getFragments();
            if(childfragments != null && childfragments.size() > 0){
                for (int j = 0; j < childfragments.size(); j++) {
                    Fragment fragment = childfragments.get(j);
                    if(fragment.getClass().isAssignableFrom(clazz)){
                        Log.i("122", "getFragment1: " + fragment);
                        return fragment;
                    }
                }
            }
        }
        return null;
    }

    private void initFragment()
    {
        fragments = new ArrayList<>();
        //通过ARouter 获取其他组件提供的fragment
        Fragment homeFragment = (Fragment) ARouter.getInstance().build(RouterFragmentPath.Home.PAGER_HOME).navigation();
        Fragment comFragment = (Fragment) ARouter.getInstance().build(RouterFragmentPath.Community.PAGER_COMMUNITY).navigation();
        Fragment messageFragment = (Fragment) ARouter.getInstance().build(RouterFragmentPath.Message.PAGE_MESSAGE).navigation();
        Fragment mineFragment = (Fragment) ARouter.getInstance().build(RouterFragmentPath.Mine.PAGE_MINE).navigation();
        fragments.add(homeFragment);
        fragments.add(comFragment);
        fragments.add(messageFragment);
        fragments.add(mineFragment);
        adapter.setData(fragments);
    }
}